package com.zb777.shuzhilingxi.controller;

import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.exception.UploadFileException;
import com.zb777.shuzhilingxi.Pojo.entity.*;
import com.zb777.shuzhilingxi.assistant.XiaozhiAgent;
import com.zb777.shuzhilingxi.service.IChatHistoryDetailService;
import com.zb777.shuzhilingxi.utils.AliOssUtil;
import com.zb777.shuzhilingxi.utils.LlamaConfig;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;;

import java.time.LocalDateTime;
@Slf4j
@RestController
@RequestMapping("/api/chat")
@Tag(name = "聊天接口")
public class ChatController {

    @Autowired
    private IChatHistoryDetailService chatHistoryDetailService;

    @Autowired
    private LlamaConfig llamaConfig;
    @Autowired
    private XiaozhiAgent xiaozhiAgent;

    @Autowired
    private AliOssUtil aliOssUtil;


    @PostMapping(value = "/normal", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    @Operation(summary = "普通聊天")
    public Flux<String> normalChat(@RequestBody ChatRequest request) {
       if (request.getImage() == null){
           xiaozhiAgent.chat(request.getChatHistoryListId(), request.getQuestion());
       }
        log.info("上传图片");
        String imageurl = aliOssUtil.processBase64Upload(request.getImage());
        Integer chatHistoryListId = request.getChatHistoryListId();
        String question = request.getQuestion();
        ChatHistoryDetail detail = new ChatHistoryDetail();
        detail.setChatHistoryListId(chatHistoryListId);
        detail.setRole("user" );
        detail.setWords(question);
        detail.setCreatedAt(LocalDateTime.now());
        detail.setIsDeleted(false);
        detail.setIsImage(false);
        detail.setImageUrl(imageurl);
        chatHistoryDetailService.save( detail);

       String text = "";
        try {
            text = llamaConfig.simpleMultiModalConversationCall(imageurl, request.getQuestion());

        } catch (NoApiKeyException | UploadFileException e) {
            throw new RuntimeException(e);
        }
        String finalText = text;
        ChatHistoryDetail detail2 = new ChatHistoryDetail();
        detail2.setChatHistoryListId(chatHistoryListId);
        detail2.setRole("system");
        detail2.setWords(finalText);
        detail2.setCreatedAt(LocalDateTime.now());
        detail2.setIsDeleted(false);
        detail2.setImageUrl(imageurl);
        chatHistoryDetailService.save( detail2);
        return Flux.create(sink -> {
            sink.next(finalText);
        });
    }
} 